<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>

    // arr=[1,1,2,3,5,8,13]
    // 递归实现斐波那契数列
    function fib(n) {
      console.count('优化前次数')
      return (n == 0 || n == 1) ? 1 : (fib(n - 1) + fib(n - 2))
    }

    fib(6)
    console.log(fib(6));


    let cache = {}
    // 用cache缓存思想优化
    function fib1(n) {
      console.count('优化后次数')
      // 如果计算过此n值
      if (cache.hasOwnProperty(n)) {
        console.count('用到缓存次数')
        return cache[n]
      }
      // 获取计算值
      let val = (n == 0 || n == 1) ? 1 : (fib1(n - 1) + fib1(n - 2))
      // 缓存进cache对象
      cache[n] = val
      return val
    }

    fib1(6)
    console.log(fib1(6));
  </script>
</body>

</html>